// pages/userSpace/address/address.js
const util = require("../../../utils/util");

Page({
  data: {
    addressId: null,
    arrProvince: [],
    arrTown: [],
    arrCity: [],
    idProvince: null,
    idCity: null,
    idTown: null,
    indexProvince: null,
    indexCity: null,
    indexTown: null,
    name: "",
    tel: "",
    addr: "",
    boolIsDefault: false,
    preAddrData: null
  },

  /* bind address information */
  bindPickerChangeProvince: function(e) {
    /* update province id and index */
    let indexProvince = e.detail.value;
    let idProvince = this.data.arrProvince[indexProvince].id;
    this.setData({ idProvince, indexProvince });
    /* clear city and town info */
    let indexCity = null;
    let idCity = null;
    this.setData({ idCity, indexCity });
    let indexTown = null;
    let idTown = null;
    this.setData({ idTown, indexTown });
    /* request city info */
    util.myRequest({
      url: util.api.regionList,
      data: { parentId: idProvince },
      success: res =>{
        this.setData({
          arrCity: res.data
        })
      }
    })
  },
  bindPickerChangeCity: function(e) {
    /* update city id and index */
    let indexCity = e.detail.value;
    let idCity = this.data.arrCity[indexCity].id;
    this.setData({ idCity, indexCity });
    /* clear town info */
    let indexTown = null;
    let idTown = null;
    this.setData({ idTown, indexTown });
    /* request town info */
    util.myRequest({
      url: util.api.regionList,
      data: { parentId: idCity },
      success: res =>{
        this.setData({
          arrTown: res.data
        })
      }
    })
  },
  bindPickerChangeTown: function(e) {
    let indexTown = e.detail.value;
    let idTown = this.data.arrTown[indexTown].id;
    this.setData({ idTown, indexTown });
  },
  bindInputName: function(e) {
    this.setData({
      name: e.detail.value
    })
  },
  bindInputTel: function(e) {
    this.setData({
      tel: e.detail.value
    })
  },
  bindInputAddr: function(e) {
    this.setData({
      addr: e.detail.value
    })
  },
  /* whether default */
  changeDefault: function() {
    let currentBool = !this.data.boolIsDefault;
    this.setData({ boolIsDefault: currentBool })
  },
  /* submit */
  addressSubmit: function() {
    let id = this.data.addressId;
    let name = this.data.name;
    let mobile = this.data.tel;
    let province_id = this.data.idProvince;
    let city_id = this.data.idCity;
    let district_id = this.data.idTown;
    let address = this.data.addr;
    let is_default = this.data.boolIsDefault;

    let isReady = (!!name)&&(!!mobile)&&(!!province_id)&&(!!city_id)&&(!!district_id)&&(!!address)
    console.log(isReady)
    if (isReady) {
      if( !!id ){
        util.myRequest({
          url: util.api.addressSave,
          method: "post",
          data: {id,name,mobile,province_id, city_id,district_id,address,is_default},
          success: res =>{
            wx.showToast({
              title: '地址修改成功',
              success: function(){
                let timer = setTimeout(()=>{
                  wx.navigateBack({
                    delta: 1
                  });
                  clearTimeout(timer);
                  timer = null;  
                }, 1600)
              }
            })
          }
        })
      } else {
        util.myRequest({
          url: util.api.addressSave,
          method: "post",
          data: {name,mobile,province_id, city_id,district_id,address,is_default},
          success: res =>{
            wx.showToast({
              title: '地址添加成功',
              success: function(){
                let timer2 = setTimeout(()=>{
                  wx.navigateBack({
                    delta: 1
                  });
                  clearTimeout(timer2);
                  timer2 = null;  
                }, 1600)
              }
            })
          }
        })
      }
    } else {
      wx.showToast({
        title: '请将地址信息填写完整',
        icon: 'none',
        duration: 2000
      })
    }
  },

  onLoad: function (options) {
    if (!!options.id) {
      let id = parseInt(options.id)
      this.initPreAddrData( id )
      .then( this.savePreAddrData )
      .then( this.initProvinceByCountryId )
      .then( this.setProvinceArray )
      .then( this.initCityByProvinceId )
      .then( this.setCityArray )
      .then( this.initDistrictByCityId )
      .then( this.setDistrictArray )
      .catch(err =>{
        console.log(err)
      })
    } else {
      util.myRequest({
        url: util.api.regionList,
        data: { parentId: 1 },
        success: res =>{
          this.setData({
            arrProvince: res.data
          })
        }
      })
    }
  },

  /* followed 8 functions: init data of current page */
  initPreAddrData: function(address_id) {
    return new Promise((resolve, reject) =>{
      util.myRequest({
        url: util.api.addressDetail,
        data: {id: address_id},
        success: res =>{
          resolve(res.data)
        },
        fail: err =>{
          reject(err)
        }
      })
    })
  },
  savePreAddrData: function(res) {
      this.setData({
        preAddrData: res,
        addressId: res.id,
        name: res.name,
        tel: res.mobile,
        addr: res.address,
        idProvince: res.province_id,
        idCity: res.city_id,
        idTown: res.district_id
      })
  },
  initProvinceByCountryId: function() {
    return new Promise((resolve, reject) =>{
      let country_id = 1;
      util.myRequest({
        url: util.api.regionList,
        data: { parentId: country_id },
        success: res =>{
          resolve(res.data)
        },
        fail: err =>{
          reject(err)
        }
      })
    })
  },
  setProvinceArray: function(res) {
    let id = this.data.preAddrData.province_id;
    let index = this.getIndexById(res, id);
    this.setData({
      arrProvince: res,
      indexProvince: index
    })
  },
  initCityByProvinceId: function() {
    return new Promise((resolve, reject) =>{
      let p_id = this.data.preAddrData.province_id;
      util.myRequest({
        url: util.api.regionList,
        data: { parentId: p_id },
        success: res =>{
          resolve(res.data)
        },
        fail: err =>{
          reject(err)
        }
      })
    })
  },
  setCityArray: function(res) {
    let id = this.data.preAddrData.city_id;
    let index = this.getIndexById(res, id);
    this.setData({
      arrCity: res,
      indexCity: index
    })
  },
  initDistrictByCityId: function() {
    return new Promise((resolve, reject) =>{
      let c_id = this.data.preAddrData.city_id;
      util.myRequest({
        url: util.api.regionList,
        data: { parentId: c_id },
        success: res =>{
          resolve(res.data)
        },
        fail: err =>{
          reject(err)
        }
      })
    })
  },
  setDistrictArray: function(res) {
    let id = this.data.preAddrData.district_id;
    let index = this.getIndexById(res, id);
    this.setData({
      arrTown: res,
      indexTown: index
    })
  },

  /* tools function */
  getIndexById: function(arrAddr, id) {
    for (let index = 0; index < arrAddr.length; index++) {
      let element = arrAddr[index];
      if( element.id == id ){
        return index;
      }
    }
  }

})